<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\api\controller\Myshopify;
use think\Db;
/**
 * 测试管理
 *
 * @icon fa fa-circle-o
 */
class ProductsShopify extends Backend
{
    
    /**
     * ProductsShopify模型对象
     * @var \app\admin\model\ProductsShopify
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\ProductsShopify;

        $this->admin = Db::name('admin')->where('id', '=', $this->auth->id)->find();

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
/**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $where2 = array();
            $type = $this->request->param('type');
            
            $where3 = array();
            if($this->admin['launch'] == 1){
                $where3['accounturl'] = ['in','55'];

                $wheregroup['createtime'] = array('elt',time());
                $wheregroup['updatetime'] = array('egt',time());
                $wheregroup['admin_id'] = $this->admin['id'];
                $accounturlgroup = Db::name('fedition_accounturlgroup')
                    ->where($wheregroup)
                    ->select();

                $accounturls = '';
                if(!empty($accounturlgroup)){
                    foreach ($accounturlgroup as $k=>$v) {
                        $accounturlgroup2[] = $v['accounturl'];
                    }
                    $accounturls = implode(',',$accounturlgroup2);
                }
                if(!empty($accounturls)){
                    $where3['accounturl'] = ['in',$accounturls];
                }
            }

            if($type == 1){
                $ytime = strtotime(date('Y-m-d')) - 1;
                $where2['updated_at']  = array('egt',$ytime);
            }

            $list = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->order($sort, $order)
                ->paginate($limit);
            $lists = $list->items();
                foreach ($lists as $k=>$v){
                    $accounturl = Db::name('fedition_accounturl')->where('id', '=', $v['accounturl'])->find();
                    if($accounturl){
                        $lists[$k]['accounturl_name'] = $accounturl['name'];
                    }else{
                        $lists[$k]['accounturl_name'] = '店铺名称已删除';
                    }
                    $shopify_variants = Db::name('products_shopify_variants')->where('product_id',$v['id'])->select();
                    $skus = '';
                    if(!empty($shopify_variants)){
                        foreach ($shopify_variants as $key=>$val) {
                            if(!empty($val['sku'])){
                                if(!empty($skus)){
                                    $skus = $skus.','.$val['sku'];
                                }else{
                                    $skus = $val['sku'];
                                }
                            }
                        }
                    }
                    $lists[$k]['skus'] = $skus;
                }

            $Statistics = array();
            $number_goods = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->count();
            $been_updat = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->where('updatestatus','normal')
                ->count();
            $not_updat = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->where('updatestatus','hidden')
                ->count();
            $update_error = $this->model
                ->where($where)
                ->where($where2)
                ->where($where3)
                ->where('updatestatus','unavailable')
                ->count();
            $Statistics['number_goods'] =  $number_goods;
            $Statistics['number_goods2'] =  $number_goods;
            $Statistics['been_updat'] =  $been_updat;
            $Statistics['been_updat2'] =  $been_updat;
            $Statistics['not_updat'] =  $not_updat;
            $Statistics['not_updat2'] =  $not_updat;
            $Statistics['update_error'] =  $update_error;
            $Statistics['update_error2'] =  $update_error;
            $result = array("total" => $list->total(), "rows" => $lists, "Statistics" => $Statistics);
            return json($result);
        }
        


        $wherea = array();
        if($this->admin['launch'] == 1){
            $wherea['id'] = ['in','55'];

            $wheregroup['createtime'] = array('elt',time());
            $wheregroup['updatetime'] = array('egt',time());
            $wheregroup['admin_id'] = $this->admin['id'];
            $accounturlgroup = Db::name('fedition_accounturlgroup')
                ->where($wheregroup)
                ->select();

            $accounturls = '';
            if(!empty($accounturlgroup)){
                foreach ($accounturlgroup as $k=>$v) {
                    $accounturlgroup2[] = $v['accounturl'];
                }
                $accounturls = implode(',',$accounturlgroup2);
            }
            if(!empty($accounturls)){
                $wherea['id'] = ['in',$accounturls];
            }
        }
        $braList = Db::name('fedition_accounturl')
            ->where('iscustom',1)
            ->where('status','normal')
            ->where($wherea)
            ->order('id desc')
            ->select();
        $this->view->assign("braList", $braList);
        return $this->view->fetch();
    }

    /**
    * 复制商品到店铺
    * @param array params
    */
    public function start()
    {
        $id = $this->request->param('ids');
        $params = $this->request->param('params');
        if(empty($id)){
            $this->error('请勾选产品');
        }
        if(empty($params)){
            $this->error('请选择店铺');
        }
        $Myshopify = new Myshopify();
        $return = $Myshopify->products_add($id,$params);
        $this->success($return);
        
    }
    
    /**
    * 手动更新
    * @param array params
    */
    public function sku_goods()
    {
        $id = $this->request->param('ids');
        
        $params = $this->request->param('params');
        if(empty($id)){
            $this->error('请勾选产品');
        }
        // if(empty($params)){
        //     $this->error('请选择店铺');
        // }
        $Myshopify = new Myshopify();
        
        $return = $Myshopify->sku_goods($id,$params);
        $this->success('更新成功');
        
    }
    /**
    * 手动更新
    * @param array params
    */
    public function needless()
    {
        $id = $this->request->param('ids');
        $params = $this->request->param('params');
        if(empty($id)){
            $this->error('请勾选产品');
        }
        // if(empty($params)){
        //     $this->error('请选择店铺');
        // }
        $Myshopify = new Myshopify();
        $return = $Myshopify->needless($id,$params);
        $this->success('更新成功');
        
    }
    /**
    * 手动更新
    * @param array params
    */
    public function synchronous()
    {
        $id = $this->request->param('ids');
        $params = $this->request->param('params');
        // if(empty($id)){
        //     $this->error('请勾选产品');
        // }
        if(empty($params)){
            $this->error('请选择店铺');
        }
        $Myshopify = new Myshopify();
        $return = $Myshopify->update_product($params);
        $this->success('更新成功');
        
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
}
